package com.yanqu.road.dao.impl.activity.unionwar;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.unionwar.BaseUnionGuessInfo;
import com.yanqu.road.entity.unionwar.UserUnionWarGuessData;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserUnionWarGuessDaoImpl extends TempDataObjectDao<UserUnionWarGuessData> {
    @Override
    protected boolean addData(UserUnionWarGuessData data) {
        PreparedStatement call = null;
        String sql = "insert into t_u_unionwar_guess(activityId,stage,userId,modifyTime,guessUnionBaseInfos) values "
                + "(?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getStage());
            call.setLong(i++, data.getUserId());
            call.setLong(i++, data.getModifyTime());
            call.setString(i++, JSON.toJSONString(data.getGuessUnionBaseInfos()));
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(UserUnionWarGuessData data) {
        PreparedStatement call = null;
        String sql = "update t_u_unionwar_guess set guessUnionBaseInfos = ?, modifyTime = ? where activityId = ? and stage = ? and userId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, JSON.toJSONString(data.getGuessUnionBaseInfos()));
            call.setLong(i++, data.getModifyTime());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getStage());
            call.setLong(i++, data.getUserId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public Map<Integer, Map<Integer, UserUnionWarGuessData>> getUserUnionWarGuessDataMap(long userId) {
        String sql = "select * from t_u_unionwar_guess where userId=?";
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Integer, UserUnionWarGuessData>> dataMap = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserUnionWarGuessData data = parse(rs);
                if (!dataMap.containsKey(data.getActivityId())) {
                    dataMap.put(data.getActivityId(), new ConcurrentHashMap<>());
                }
                dataMap.get(data.getActivityId()).put(data.getStage(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    @Override
    protected UserUnionWarGuessData parseData(ResultSet rs) throws SQLException {
        UserUnionWarGuessData data = new UserUnionWarGuessData();
        data.setUserId(rs.getLong("userId"));
        data.setActivityId(rs.getInt("activityId"));
        data.setStage(rs.getInt("stage"));
        data.setModifyTime(rs.getLong("modifyTime"));
        String guessUnionBaseInfoStr = rs.getString("guessUnionBaseInfos");
        if(!StringUtils.isNullOrEmpty(guessUnionBaseInfoStr)){
            List<BaseUnionGuessInfo> guessUnionBaseInfos = JSON.parseObject(guessUnionBaseInfoStr, new TypeReference<List<BaseUnionGuessInfo>>() {});
            if(null != guessUnionBaseInfos) {
                data.setGuessUnionBaseInfos(guessUnionBaseInfos);
            }
        }
        return data;
    }
}
